package com.delicaterock.mpw;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class PPTScreen extends AbstractActivity {
    private String url;
    private String ips;
    private String port;
    private String secret;
    private String app;
	private PlayPPT thread;
	private TextView txtInfo;

    @Override 
    public void onDestroy() {
    	super.onDestroy();
    	if (thread!=null && thread.handler!=null) {
    		thread.handler.obtainMessage(R.id.quit).sendToTarget();
    	}
    }
    
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ppt);
        
        Intent i = this.getIntent();
        url = i.getStringExtra("url");

        
        
        if (null==url || url.length()==0) {
        	url = "mpw://127.0.0.1:4444@0/unknown";	// sth. wrong
        }
        
        txtInfo = (TextView)findViewById(R.id.txt_info);
        
        Button btnNext = (Button) findViewById(R.id.btn_next);
        btnNext.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				if (thread!=null && thread.isAlive() && thread.handler!=null) {
					thread.handler.obtainMessage(R.id.next).sendToTarget();
				}
			}});

        Button btnPrevious = (Button) findViewById(R.id.btn_previous);
        btnPrevious.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				if (thread!=null && thread.isAlive() && thread.handler!=null) {
					thread.handler.obtainMessage(R.id.previous).sendToTarget();
				}
			}});
        
        thread = new PlayPPT();
        thread.start();        
        
    }
	
	private final Handler caller = new Handler() {
		@Override
		public void handleMessage(Message msg) {
        	switch(msg.what) {
        	case R.id.ready:
        		txtInfo.setText("Connected...");
        		break;
        	case R.id.error:
        		txtInfo.setText("Error!");
        		break;
        	case R.id.next:
        		txtInfo.setText("Moved to the next page.");
        		break;
        	case R.id.previous:
        		txtInfo.setText("Moved to the previous page.");
        		break;        		
        	}
		}
	};
	
	private class PlayPPT extends  Thread {
		public Handler handler = null;
		private OutputStreamWriter out = null;
		private Socket socket;
		
		@Override
		public void run() {
			try {
				if (url.startsWith("mpw://")) {
					String prefixRemoved = url.replaceFirst("mpw://", "");
					ips = prefixRemoved.substring(0, prefixRemoved.indexOf(":"));
					port = prefixRemoved.substring(prefixRemoved.indexOf(":")+1, prefixRemoved.indexOf("@"));
					secret = prefixRemoved.substring(prefixRemoved.indexOf("@")+1, prefixRemoved.indexOf("/"));
					app = prefixRemoved.substring(prefixRemoved.indexOf("/")+1, prefixRemoved.length());
					Log.d("handleUrl():", String.format("ips:%s,port:%s,secret:%s,app:%s", ips, port, secret, app));
					String[] iplist = ips.split(",");
					handler = null;
					socket = null;
					out = null;
					playPPT(iplist);
				}
			} catch (Exception e) {
				caller.obtainMessage(R.id.error).sendToTarget();
				e.printStackTrace();
			}
		}
		
		private void playPPT(String[] ipList) {		
			ArrayList<String> list = SimpleDBHelper.sortIPs(ipList);
			for (int i=0; i<list.size(); i++) {	
				Log.d("","connecting "+list.get(i));
				try {
					InetAddress ip = InetAddress.getByName(list.get(i));
					if (!ip.isLoopbackAddress()) {	
							socket = new Socket();
							socket.connect(new InetSocketAddress(ip, Integer.parseInt(port)), 3000);
							out = new OutputStreamWriter(socket.getOutputStream(), "utf8");
							Log.d("","connected "+list.get(i));
					}					
				} catch (Exception e) {
					e.printStackTrace();
					continue;
				}
				
				if (out!=null) {
					caller.obtainMessage(R.id.ready).sendToTarget();
			        Looper.prepare();
			        
			        handler = new Handler() {
			            public void handleMessage(Message msg) {
			            	Log.d("handler", "message...");
			            	String opt = "next";
			            	String payload = "";
			            	try {
				            	switch(msg.what) {
				            	case R.id.next:
				    				payload = String.format("[mpw:%s]%s\n", secret, opt);
				    				if (out!=null) {
				    					out.write(payload);
				    					out.flush();
				    					Log.d("handler", "message...next");
				    					caller.obtainMessage(R.id.next).sendToTarget();
				    				}
				            		break;
				            	case R.id.previous:
				            		opt = "previous";
				    				payload = String.format("[mpw:%s]%s\n", secret, opt);
				    				if (out!=null) {
				    					out.write(payload);
				    					out.flush();
				    					Log.d("handler", "message...previous");
				    					caller.obtainMessage(R.id.previous).sendToTarget();
				    				}
				            		break;
				            	case R.id.quit:
				            		if (out!=null && socket!=null) {
				            			out.close();
				            			socket.close();
				            		}
				            		Looper.myLooper().quit();
				            		break;
				            	}	
			            	} catch (Exception e) {
			            		e.printStackTrace();
			            		caller.obtainMessage(R.id.error).sendToTarget();
			            	}
			            }
			        };	
			        
			        Looper.loop();
				}				
			}		
		}	
		
	}	
}
